package com.sunyur.tailor.channel.service.outer.keep.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyur.tailor.channel.common.inner.base.MsgResultCode;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.common.middle.util.RestTemplateUtil;
import com.sunyur.tailor.channel.dal.org.entity.FSBackDO;
import com.sunyur.tailor.channel.dal.org.mapper.FSBackMapper;
import com.sunyur.tailor.channel.service.outer.keep.param.SRMPurchaseFeishuForApprovalParam;
import com.sunyur.tailor.channel.service.outer.keep.service.KeepToFeishuService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.http.HttpURI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  Keep 对接飞书 提交操作 Service
 */
@Service("keepToFeishuService")
@Slf4j
public class KeepToFeishuServiceImpl implements KeepToFeishuService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(RestTemplateUtil.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(RestTemplateUtil.class);

    @Value("${feishu.key}")
    private String key;

    @Value("${feishu.secret}")
    private String secret;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Value("${feishu.strategyOrderUrl}")
    private String strategyOrderUrl;

    @Value("${feishu.getAuthUrl}")
    private String getAuthUrl;

    @Autowired
    private FSBackMapper fsBackMapper;

    @Override
    public ChannelResult<Boolean> sRMPurchaseFeishuForApproval(MsgResultCode msgResultCode,SRMPurchaseFeishuForApprovalParam srmPurchaseFeishuForApprovalParam) {

        log.info("SRMPurchaseFeishuForApprovalParam:{}", JSON.toJSONString(srmPurchaseFeishuForApprovalParam));

        JSONObject result = exchangeJsonPost(srmPurchaseFeishuForApprovalParam,strategyOrderUrl,getAuthorization());
        log.info("SRMPurchaseFeishuForApproval result:{}",result);
        if(Objects.equals(result.get("code"), 0)) {
            //存入数据库
            FSBackDO fsBackDO =new FSBackDO();
           //已存在数据库
            FSBackDO f = fsBackMapper.selectOne(new QueryWrapper<FSBackDO>().eq("business_code", msgResultCode.getBusinessCode()));
            if(!Objects.isNull(f))
            {
                f.setInstanceCode(result.getJSONObject("data").getString("instance_code"));
                f.setModifyTime(null);
                fsBackMapper.updateById(f);
            }else {
                fsBackDO.setWorkflowBusiness(msgResultCode.getWorkflowBusiness());
                fsBackDO.setInstanceCode(result.getJSONObject("data").getString("instance_code"));
                fsBackDO.setAction(msgResultCode.getAction());
                fsBackDO.setBusinessCode(msgResultCode.getBusinessCode());

                int insert = fsBackMapper.insert(fsBackDO);
                log.info("fsBackDO insert into db test {}",insert);
            }

            return ChannelResultUtil.success(true);
        }
        else {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(),result.get("msg").toString());
        }

    }

    @Override
    public JSONObject exchangeJsonPost(Object t, String url,String authorization) {
        URI uri = URI.create(url);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Authorization", authorization);
        HttpEntity<Object> httpEntity = new HttpEntity<>(t, headers);
        LOGGER_INFO.info("exchangeJsonPost.param:{},url:{}", JSON.toJSONString(httpEntity), url);
        ResponseEntity<String> stringResponseEntity;
        JSONObject responseEntity = null;
        try {
            stringResponseEntity = restTemplate.postForEntity(uri, httpEntity, String.class);
            LOGGER_INFO.info("exchangeJsonPost stringResponseEntity is {}", JSON.toJSONString(stringResponseEntity));
            if (stringResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                responseEntity = JSON.parseObject(stringResponseEntity.getBody());
            }
        } catch (RestClientException e) {
            LOGGER_ERROR.error("exchangeJsonPost.exception：{}", e);
        }
        LOGGER_INFO.info("exchangeJsonPost.return:{}", JSON.toJSONString(responseEntity));
        return responseEntity;
    }


    @Override
    public String getAuthorization(){
        Map to =new HashMap();
        to.put("app_id",key);
        to.put("app_secret",secret);

        JSONObject result = restTemplateUtil.exchangeJsonPost(to,getAuthUrl);
        if(result.getInteger("code")==0){
            log.info("飞书Token: "+"Bearer "+result.getString("tenant_access_token"));
            return "Bearer "+result.getString("tenant_access_token");
        }
        log.info("getAuthorization result:{}",result);
        return null;
    }
}
